/**
 * Created by ZFL on 2017/9/28.
 */
var payType;
function appInit() {
    PageInit();
}
function PageInit() {
    //蚂蚁支付手机号码
    if ($.getStorage("hx_uData")) {
        vm.userName = JSON.parse($.getStorage("hx_uData")).userName;
    }
    vm.userName = vm.userName.substring(0, 3) + '****' + vm.userName.substring(7, 11);
}

var vm = new Vue({
    el: "#app",
    data: {
        orderData: {},
        userName: '',//用户的手机号码
        mobileCode: '',//蚂蚁支付手机验证码
        orderObjectId: '',//父订单id
        payType: '',    //支付方式(1.微信支付2.支付宝支付3.公众号支付4.景豆5蚂蚁钱包6支付宝网页支付)
        saleTotal: 0,//总价
        payTypeList:[],     //支付方式
        balancePrice: ''//蚂蚁支付账户余额
    },
    filters: function () {
        //内置过滤器
    },
    mounted: function () {
        this.$nextTick(function () {
            //初始化
            this.cartView();
        });
    },
    methods: {
        cartView: function () {
            orderInfo();
        },
        cancelOrder: function () {
            $.ajaxHandler({
                model: function () {
                    var obj = {};
                    if(vm.orderObjectId == ''){
                        obj.orderObjectId = 0;
                    }else {
                        obj.orderObjectId = vm.orderObjectId;//父订单ID
                    }
                    obj.userId = com_obj.userId;
                    return obj;
                },
                visibleTime: 0,
                dataType: "json",
                approve: true,
                api: "yg_baijiaplatform/order/cancelOrder",
                success: function (result) {
                    //console.log(result);
                    if (result.code == 10000) {
                        YDUI.dialog.toast('取消订单成功', 'success', function () {
                        });
                        setTimeout(function () {
                            window.location.href = '/b2c/order/order.html'
                        }, 1000)
                    } else {
                        YDUI.dialog.toast(result.message, 'error', function () {
                        });
                    }
                }
            });
        },
        account: function (orderSn) {
            switch (vm.payType) {
                case 3: //公众号支付
                    weChaPa(orderSn);
                    break;
                case 6://支付宝网页支付
                    Alipay(orderSn);
                    break;
                case 4:
                    //景豆支付
                    $(".jd-layer").show();
                    $(".jd-container").show();
                    jdChapa(orderSn); //景豆支付
                    break;
            }
        },
        setPayWay:function(item){
            this.payList.forEach(function(value,index){
                value.payYesNo = false;
            });
            item.payYesNo = true;
            this.payType = item.payType;
        }
    }
});
var payImages = {
    '1':'../images/pay/weixinzhifu@2x.png',
    '4':'/src/images/pay/jingdou_pay_icon.png',
    '2':'../images/pay/zhifubaozhifu@2x.png'
};
//加载订单详情
function orderInfo() {
    $.ajaxHandler({
        model: function () {
            var obj = {};
            obj.appOrH5 = 1;// 0App默认值,1h5必传)
            obj.orderSn = $.getPara("orderSn");
            return obj;
        },
        visibleTime: 0,
        dataType: "json",
        approve: true,
        api: "yg_baijiaplatform/orderObject/getOrderObjectEntityByOrderSn",
        success: function (result) {
            //console.log(result);
            if (result.code == 10000) {
                var obj = {};
                var data = result.data;
                vm.orderObjectId = data.orderObjectId;
                vm.payType = data.payType;
                obj.idNumber = data.idNumber;//身份证标识 0是普通1是海淘
                //obj.idNumber = 1;
                obj.orderSn = data.orderSn;//订单编号
                obj.createTime = data.createTime.toString().substr(0, 19);
                obj.linkMan = data.linkMan;//收货人
                obj.mobile = data.mobile;//手机号
                obj.address = data.province + data.city + data.area + data.address;//收货地址
                obj.promotionDiscount = divideNumber(data.promotionDiscount, 100);//优惠券
                obj.cashCoin = divideNumber(data.cashCoin, 100);//消费券
                obj.orderObjectId = data.orderObjectId;//父订单ID
                if (data.billHeader.toString() == "") {//发票
                    obj.billHeader = "无";
                } else {
                    obj.billHeader = data.billHeader;
                }
                if (data.remark.toString() == "") {//留言
                    obj.remark = "无";
                } else {
                    obj.remark = data.remark;
                }
                var orders = [];
                if (data.orderInfoVoList.length > 0) {
                    $.each(data.orderInfoVoList, function (index, item) {
                        var obj1 = {};
                        obj1.logoPath = item.logoPath;//店铺logo
                        obj1.storeName = item.storeName;//店铺名称
                        obj1.deliveryWay = item.deliveryWay;//配送方式1快递送2及时送3到店取
                        if (item.deliveryWay == 1) {
                            obj1.deliveryTex = '及时送';
                        } else if (item.deliveryWay == 3) {
                            obj1.deliveryTex = '快递送';
                        }else if (item.deliveryWay == 2) {
                            obj1.deliveryTex = '到店取';
                        }
                        obj1.freight = divideNumber(item.freight, 100);//运费
                        var arr = [];
                        if (item.listOrderDetail.length > 0) {
                            $.each(item.listOrderDetail, function (j, rows) {
                                var cobj = {};
                                cobj.goodName = rows.goodName;//商品名称
                                cobj.navigateImg1 = rows.navigateImg1;//商品图片
                                cobj.specName = rows.specName;//规格
                                cobj.salePrice = divideNumber(rows.salePrice, 100);//商品售价
                                cobj.quantity = rows.quantity;//数量
                                arr.push(cobj);
                            })
                        }
                        obj1.listOrderDetail = arr;
                        orders.push(obj1);
                    })
                }
                obj.orderList = orders;
                if (data.totalFee.toString() == 0) {
                    obj.totalFee = 0.01;
                    vm.saleTotal = 0.01;
                } else {
                    obj.totalFee = divideNumber(data.totalFee, 100);//
                    vm.saleTotal = divideNumber(data.totalFee, 100);
                }
                //判断支付方式
                vm.payTypeList = [];    //支付方式数组

                //1.微信支付2.支付宝支付3.公众号支付4.景豆5蚂蚁钱包 6支付宝网页支付
                data.payTypeConfigList.forEach(function(value,index){

                    console.log(!$.isWX())
                    if(value.id==3&&$.isWX()){
                        value.picturePath='../images/pay/weixinzhifu@2x.png'
                        vm.payWay = value.payType;
                        vm.payTypeList.push(value);

                    }else if(value.id==5&&!$.isWX()){
                        value.picturePath='../images/pay/zhifubaozhifu@2x.png';
                        vm.payWay = value.payType;
                        vm.payTypeList.push(value);
                    }


                });
                vm.$set(vm, "orderData", obj);
            } else {
                YDUI.dialog.toast(result.message, 'error', function () {
                });
            }
        }
    });
}

//微信支付
function weChaPa(orderSn){
    var obj ={};
    obj.openId  = $.getStorage('userOpenid');
    obj.orderSn = orderSn;
    obj.payType = 3;        //公众号支付
    console.log(obj)
    $.ajaxHandler({
        model: function () {
            return obj;
        },
        visibleTime: 100,
        visible:'hide',
        approve: true,
        api:"yg_baijiaplatform/wecha/weChaPay",
        success: function (result) {
            //console.log(result);
            if (result.code == 10000) {
                var data = result.data;
                if(data.paySign){
                    onBridgeReady(data);
                }else {
                    //支付失败
                    _status = false;
                    YDUI.dialog.toast(result.message, 'error', 1000);
                }
            }else {
                _status = false;
                YDUI.dialog.toast(result.message, 'error', 1000);
            }
        }
    });
}

//微信统一下单
function onBridgeReady(data) {
    WeixinJSBridge.invoke('getBrandWCPayRequest', {
            "appId":""+data.appid+"",//公众号名称，由商户传入
            "timeStamp":""+data.timeStamp+"",//时间戳，自1970年以来的秒数
            "nonceStr":""+data.nonce_str+"", //随机串
            "package":"prepay_id="+data.prepay_id+"",
            "signType":"MD5",//微信签名方式：
            "paySign":""+data.paySign+"" //微信签名
        },
        function(res){
            // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回
            // ok，但并不保证它绝对可靠。
            //alert(res);
            //console.log(res)
            //alert(res.err_msg);
            //$.delStorage('orderObject');
            if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                //console.log('成功');
                location.href ='./pay_success.html?payType=3&orderSn='+vm.orderData.orderSn+'&orderObjectId='+vm.orderObjectId;
            }else{
                //console.log('失败');
                location.href ='./pay_error.html?payType=3&orderSn='+vm.orderData.orderSn+'&orderObjectId='+vm.orderObjectId;
            }
        }
    );
}

//支付宝支付
function  Alipay(orderSn){
    $.ajaxHandler({
        model: function () {
            var obj ={};
            obj.orderSn = orderSn;
            obj.payType = 6;//支付宝网页版支付
            obj.showUrl = $.wxApi()+'./pay/pay_error.html?orderSn='+orderSn+'';
            obj.returnUrl = $.wxApi()+'./pay/pay_success.html';
            console.log(obj)
            return obj;
        },
        visibleTime: 100,
        visible:'hide',
        approve: true,
        api:"yg_baijiaplatform/alipay/getOrderString",
        success: function (result) {
            console.log(result);
            if (result.code == 10000) {
                var data = result.data;
                window.localStorage.setItem("orderSn",orderSn);
                //支付成功
                if(data){
                    onAlipayBridgeReady(data);
                }
                //console.log('成功');
                //location.href ='./pay_successed.html';
            }else {
                //支付失败
                console.log('失败');
                //location.href ='./pay_error.html';
                YDUI.dialog.toast(result.message, 'error', 1000);
            }
        }
    });
}

//支付宝统一下单
function onAlipayBridgeReady(data){
    //console.log(data.service);
    //var return_url =  $.wxApi()+'b2c/pay/pay_successed.html';
    var httPurl ='http://mapi.alipay.com/gateway.do?_input_charset=utf-8&body='+data.body+'&it_b_pay='+data.it_b_pay+'&notify_url='+data.notify_url+'&out_trade_no='+data.out_trade_no+'&partner='+data.partner+'&payment_type='+data.payment_type+'&return_url='+data.return_url+'&seller_id='+data.seller_id+'&service='+data.service+'&show_url='+data.show_url+'&subject='+encodeURI(data.subject)+'&total_fee='+data.total_fee+'&sign='+data.sign+'&sign_type='+data.sign_type;
    window.location.href=httPurl;
}
//返回上一页
function returnBack() {
    window.history.back();  //返回上一页
}








